<!--
    by: yuanbiao 2021年06月11日
    name: x-text-viewer
    notes:
-->
<template>
  <pre :class="[`${prefixCls}`]">{{filedata}}</pre>
</template>

<script>
import Toast from '@/components/toast/index.js'
import {isArrayBuffer, typeOf} from '@/script/utils.js'
const axios = require('axios')
const iconv = require('iconv-lite')
const prefixCls = 'x-text-viewer'
export default {
  name: 'x-text-viewer',
  props: {
    options: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      prefixCls: prefixCls,
      filedata: ''
    }
  },
  watch: {
    options: {
      handler (n) {
        this.getFileData(n.url)
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    getFileData (url) {
      this.filedata = ''
      let _this = this
      let decode = this.options.decode || 'cp936'
      let responseType = /.(json)$/i.test(this.options.label) ? 'json' : 'arraybuffer'
      axios.get(url, { responseType }).then((res) => {
        try {
          if (isArrayBuffer(res.data)) {
            let txt = String.fromCharCode.apply(null, new Int8Array(res.data))
            _this.filedata = iconv.decode(txt, decode)
          } else if (typeOf(res.data) === 'Object') {
            _this.filedata = JSON.stringify(res.data)
          } else if (typeOf(res.data) === 'String') {
            _this.filedata = res.data
          }
        } catch (err) {
          let message = (err || {}).message || '未知错误'
          Toast(`发生错误：${message}`)
        }
      })
    }
  }
}
</script>
